<!--
 * @Description: 
 * @Author: chenju
 * @Date: 2022-03-22 17:08:41
 * @LastEditors: qingyang
 * @LastEditTime: 2023-07-24 10:54:29
-->
<template>
  <CDialog
    :title="title"
    v-model:visible="dialogVisible"
    @confirm="handleConfirm"
    @cancel="dialogVisible = false"
    :loading="loading"
    size="small"
  >
    <el-form ref="formRef" :model="taskForm" :rules="rules" label-position="top">
      <el-row>
        <el-col :span="24">
          <el-form-item :label="productIdLabel" prop="productId">
            <el-input v-model="taskForm.productId" placeholder="请输入" />
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="车型名称" prop="productName">
            <el-input v-model="taskForm.productName" placeholder="请输入" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="车型公告号" prop="productModel">
            <el-input v-model="taskForm.productModel" placeholder="请输入" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="车型描述" prop="productDesc">
            <el-input v-model="taskForm.productDesc" placeholder="请输入" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="企业名称" prop="enterpriseNo">
            <CSelect v-model="taskForm.enterpriseNo" placeholder="请选择" @change="changeCompany">
              <el-option
                v-for="option in companyList"
                :key="option.enterpriseNo"
                :label="option.enterpriseName"
                :value="option.enterpriseNo"
              />
            </CSelect>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="版本" prop="version">
            <el-input v-model="taskForm.version" placeholder="请输入" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </CDialog>
</template>
<script lang="ts">
export default {
  name: 'AddOrEditBomProductDialog'
};
</script>
<script lang="ts" setup>
import { defineProps, withDefaults, defineEmits, computed, ref, watch, reactive } from 'vue';
import { CDialog } from '@/components/CDialog';
import { CSelect } from '@/components/CSelect';

import { useMessage } from '@/hooks/useMessage';
import { rules } from './rules';
import { store } from '@/store';
import type { IAddBomProduct } from '@/apis/system/config/model/bomProductModel';
import {
  createBomProduct,
  editBomProduct,
  getBomProductDetail
} from '@/apis/system/config/bomProduct';
import type { IEnterprise } from '@/apis/user/model/userModel';
import { getEnterpriseList } from '@/apis/user/user';

const companyList = ref<IEnterprise[]>([]);
const formRef = ref();
const loading = ref(false);
const taskForm = reactive({
  productId: '',
  productModel: '',
  productName: '',
  productDesc: '',
  version: '',
  enterpriseNo: '',
  enterpriseName: ''
});
const loadCompanyList = async () => {
  let data = await getEnterpriseList();
  if (userInfo.value.enterpriseNo !== 'C0000001') {
    //C0000001表示根组织, 如果不是根组织就过滤
    data = data.filter(item => userInfo.value.enterpriseNo == item.enterpriseNo);
  }
  companyList.value = data ?? [];
  if (props.type !== 'EDIT') {
    taskForm.enterpriseNo = companyList.value.length == 1 ? companyList.value[0].enterpriseNo : '';
    taskForm.enterpriseName =
      companyList.value.length == 1 ? companyList.value[0].enterpriseName : '';
  }
};
loadCompanyList();
interface SelectFillTypeDialogProps {
  visible: boolean;
  // 提交类型
  type: 'ADD' | 'EDIT';
  // 当前产品编号，编辑时必传
  productNo?: string;
}
const props = withDefaults(defineProps<SelectFillTypeDialogProps>(), {
  visible: false,
  type: 'ADD'
});
const emit = defineEmits(['update:visible', 'refresh']);

const { createMessage } = useMessage();

const dialogVisible = computed<boolean>({
  get: () => {
    return props.visible;
  },
  set: val => {
    emit('update:visible', val);
  }
});
watch(
  () => dialogVisible.value,
  visible => {
    if (!visible) {
      // 关闭时清空数据
      handleClear();
    } else {
      // 打开时初始化新数据
      initVisible();
    }
  }
);
const title = computed(() => {
  return props.type === 'EDIT' ? '编辑车型' : '新增车型';
});
const userInfo = computed(() => {
  return store.state.user.userInfo;
});
const isEditTask = computed(() => {
  return !!(props.type === 'EDIT');
});
const productIdLabel = computed(() => {
  return window.GLOBAL_FIELD_TO_TEXT?.productId || '车型ID';
});

// 提交按钮
function handleConfirm() {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      submitTaskReq();
    }
  });
}

// 请求接口
async function submitTaskReq() {
  try {
    loading.value = true;
    const params: IAddBomProduct = {
      productId: taskForm.productId,
      productModel: taskForm.productModel,
      productName: taskForm.productName,
      productDesc: taskForm.productDesc,
      version: taskForm.version,
      enterpriseNo: taskForm.enterpriseNo,
      enterpriseName: taskForm.enterpriseName
    };
    if (isEditTask.value) {
      Object.assign(params, {
        productNo: props.productNo
      });
      await editBomProduct(params);
    } else {
      await createBomProduct(params);
    }
    createMessage.success(`${isEditTask.value ? '编辑' : '新增'}车型成功`);
    dialogVisible.value = false;
    loading.value = false;
    emit('refresh');
  } catch (error) {
    loading.value = false;
  }
}
const changeCompany = (val: string) => {
  const index = companyList.value.findIndex(item => item.enterpriseNo == val);
  if (index > -1) {
    taskForm.enterpriseName = companyList.value[index].enterpriseName;
  }
};
// 关闭时清空数据
function handleClear() {
  loading.value = false;
  formRef.value?.resetFields();
  taskForm.productId = '';
  taskForm.productModel = '';
  taskForm.productName = '';
  taskForm.productDesc = '';
  taskForm.version = '';
}

// 打开时初始化
async function initVisible() {
  if (props.type === 'EDIT' && props.productNo) {
    try {
      const info = await getBomProductDetail(props.productNo);
      taskForm.productId = info.productId;
      taskForm.productModel = info.productModel;
      taskForm.productName = info.productName;
      taskForm.productDesc = info.productDesc;
      taskForm.version = info.version;
      taskForm.enterpriseNo = info.enterpriseNo;
      taskForm.enterpriseName = info.enterpriseName;
    } catch (error) {
      console.log('error', error);
    }
  } else {
    handleClear();
  }
}
</script>
